package com.efounder.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.builder.base.data.EFRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.view.titlebar.AbTitleBar;
import com.pansoft.espcomp.ESPWebView;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;


/**
 * @author Lch
 */
public class NoticeDetailActivity extends Activity {

    /*private StubObject mMenuItem;*/
    private String titleStr;
    EFRowSet efRowset;
    //	CustomProgressDialog dialog;
    private View rootView;// 缓存Fragment view
    AbTitleBar title;
    ESPWebView web;
    String webUrl;
    Boolean isShowBottom;
    Activity activity;
    private boolean isReload = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //EFTitleBar efTitleBar = new EFTitleBar(this);
        rootView = getLayoutInflater().inflate(R.layout.webviewwithrowset, null);

        efRowset = (EFRowSet) getIntent().getSerializableExtra("rowset");
        if (null != efRowset)
            webUrl = efRowset.getString("F_URL", "");
        RelativeLayout include = (RelativeLayout) rootView.findViewById(R.id.include);
        TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);
        title.setText("新闻详情");
        LinearLayout leftbacklayout = (LinearLayout) rootView.findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);

        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                NoticeDetailActivity.this.finish();
            }
        });

        Button rightButton = (Button) rootView.findViewById(R.id.closeButton);
        // 获取

        // 设置

        rightButton.setVisibility(View.INVISIBLE);
        rightButton.setBackgroundResource(R.drawable.sharebutton);
        rightButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            /*	Toast.makeText(activity, String.valueOf(webUrl),
                        Toast.LENGTH_SHORT).show();*/

                String xwbt = efRowset.getString("F_XWBT", "");
                String imagePath = Environment.getExternalStorageDirectory().toString() + "/" +
                        EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                        + "/res" + "/unzip_res" + "/Image" + "/ic_launcher.png";
                /*OnekeyShare oks = new OnekeyShare();
                oks.setTitle(xwbt);
				oks.setTitleUrl(webUrl);
				oks.setText(webUrl);
				oks.setUrl(webUrl);
				//oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
				oks.setImagePath(imagePath);

				 oks.setSilent(true); // 隐藏编辑页面

				//oks.setSilent(false); // 显示编辑页面
				// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
				oks.show(NoticeDetailActivity.this);*/
            }
        });


        web = (ESPWebView) rootView.findViewById(R.id.mywebview);

        web.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {  //表示按返回键 时的操作
                        NoticeDetailActivity.this.finish();
                        return true;    //已处理
                    }
                }
                return false;
            }
        });
        //web.getSettings().setUseWideViewPort(true);
        //web.getSettings().setLoadWithOverviewMode(true);
        web.addJavascriptInterface(new ComJSInterface(), "comjs");
        web.getSettings().setJavaScriptEnabled(true);
        web.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isReload) {
                    //  view.loadUrl()
                    return;
                }
                view.loadUrl("javascript:window.comjs.loadHtmlContent(document.documentElement.outerHTML);void(0)");

            }

        });


        webUrl = handleURL(webUrl);
        web.loadUrl(String.valueOf(webUrl));
        setContentView(rootView);
    }

    public class ComJSInterface {
        @JavascriptInterface
        public void loadHtmlContent(final String content) {
            Log.i("comJs------", "html:" + content);
            final String a = content.replace("width=\"590\"", "width=\"100%\"");
            isReload = true;
            web.post(new Runnable() {
                @Override
                public void run() {
                    //web.loadData(a, "text/html", null);
                    web.loadDataWithBaseURL(null, a, "text/html", "utf-8", null);
                }
            });
        }
    }

    private class webClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //	dialog.show();
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LoadingDataUtilBlack.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LoadingDataUtilBlack.show(NoticeDetailActivity.this);
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            handler.proceed();// 接受证书
            LoadingDataUtilBlack.dismiss();
        }
    }

    /**
     * 拦截处理url
     *
     * @param url
     * @return
     */
    private String handleURL(String url) {
        String matchURL = "http://10.80.0.104:8080/EnterpriseServer";
        if (url != null && url.contains(matchURL)) {
            //StorageUtil storageUtil = new StorageUtil(this, "storage");
            String serverURL = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                    + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
            url = url.replace(matchURL, serverURL);
        }
        return url;
    }


}
